package cn.xiangxiang.service.impl;

import cn.xiangxiang.mapper.UserMapper;
import cn.xiangxiang.pojo.user.TbUser;
import cn.xiangxiang.service.user.UserService;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service(interfaceClass = UserService.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, TbUser> implements UserService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public TbUser findUserByUserName(TbUser user) {

        QueryWrapper<TbUser> wrapper = getCondition(user);
        TbUser tbUser = getOne(wrapper);

        return tbUser;
    }

    /**
     * 短信发送服务
     * 发送给rabbitMQ 和 redis
     * */
    public void sendSms(String phone) {

        Random random = new Random();
        int ranCode = random.nextInt(999999);
        if(ranCode<100000){
            ranCode+=100000;
        }


        HashMap<String, Object> map = new HashMap<>();
        map.put("phone",phone);
        map.put("code",ranCode);

        System.out.println(map);

        rabbitTemplate.convertAndSend("xiangxiang.sms", JSON.toJSONString(map));

        redisTemplate.boundValueOps("sms_"+phone).set(ranCode);
        redisTemplate.boundValueOps("sms_"+phone).expire(5, TimeUnit.MINUTES);

    }

    /**
     * 账号注册
     * */
    public void addUser(String code, TbUser user) {
        Integer redisCode = (Integer) redisTemplate.boundValueOps("sms_"+user.getPhone()).get();
        if(redisCode==null){
            throw  new RuntimeException("请先获取验证码");
        }
        if(!code.equals(redisCode.toString())){
            throw  new RuntimeException("验证不正确");
        }

        user.setUsername(user.getPhone());
        user.setCreated(new Date());
        user.setStatus("1");
        user.setIsMobileCheck("1");
        user.setUpdated(new Date());
        user.setUserLevel(1);
        user.setPoints(100);
        user.setExperienceValue(0);
        user.setLastLoginTime(new Date());
        save(user);

    }

    private QueryWrapper<TbUser> getCondition(TbUser user){
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        if(user!=null){
            if(user.getUsername()!=null && !"".equals(user.getUsername())){
                wrapper.eq("username",user.getUsername());
            }
        }
        return wrapper;
    }
}
